#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
自动运行Frida并捕获EP加密数据
"""

import frida
import sys
import time
import json
import re

# 目标应用
PACKAGE_NAME = "com.mcdonalds.gma.cn"

# 读取JS脚本
with open('verify_rsa_key.js', 'r', encoding='utf-8') as f:
    js_code = f.read()

print("=" * 80)
print("🚀 启动Frida Hook - 捕获EP加密")
print("=" * 80)
print(f"目标应用: {PACKAGE_NAME}")
print()

# 捕获的数据
captured_data = {
    'aes_key': None,
    'iv': None,
    'ep_plaintext': None,
    'rsa_key_info': None
}

def on_message(message, data):
    """处理Frida消息"""
    global captured_data
    
    if message['type'] == 'send':
        payload = message.get('payload', '')
        print(payload)
        
        # 尝试提取AES密钥
        if 'AES_set_encrypt_key' in payload or '密钥:' in payload:
            match = re.search(r'密钥:\s*([0-9a-fA-F]{64})', payload)
            if match:
                captured_data['aes_key'] = match.group(1)
                print(f"\n✅ 捕获到AES密钥: {captured_data['aes_key']}\n")
        
        # 尝试提取IV
        if 'IV:' in payload:
            match = re.search(r'IV:\s*([0-9a-fA-F]{32})', payload)
            if match:
                captured_data['iv'] = match.group(1)
                print(f"\n✅ 捕获到IV: {captured_data['iv']}\n")
        
        # 检查是否捕获完整
        if captured_data['aes_key'] and captured_data['iv']:
            print("\n" + "=" * 80)
            print("🎉 捕获完成！")
            print("=" * 80)
            print(f"AES密钥: {captured_data['aes_key']}")
            print(f"IV: {captured_data['iv']}")
            print("=" * 80)
            
            # 保存到文件
            with open('captured_keys.txt', 'w') as f:
                f.write(f"AES密钥: {captured_data['aes_key']}\n")
                f.write(f"IV: {captured_data['iv']}\n")
            
            print("\n✅ 密钥已保存到 captured_keys.txt")
            print("\n下一步: 使用这些密钥解密data字段")
            
    elif message['type'] == 'error':
        print(f"❌ 错误: {message.get('stack', message)}")

try:
    # 连接设备
    print("📱 连接设备...")
    device = frida.get_usb_device()
    print(f"✓ 设备: {device}")
    
    # 检查应用是否在运行
    try:
        print(f"\n📱 检查应用状态...")
        running = False
        for process in device.enumerate_processes():
            if PACKAGE_NAME in process.name or PACKAGE_NAME == process.name:
                running = True
                print(f"✓ 应用正在运行 (PID: {process.pid})")
                break
        
        if running:
            print(f"\n🔗 附加到正在运行的应用...")
            session = device.attach(PACKAGE_NAME)
        else:
            print(f"\n🚀 启动应用...")
            pid = device.spawn([PACKAGE_NAME])
            session = device.attach(pid)
            device.resume(pid)
            print(f"✓ 应用已启动 (PID: {pid})")
    
    except Exception as e:
        print(f"⚠️  应用未运行，尝试启动...")
        pid = device.spawn([PACKAGE_NAME])
        session = device.attach(pid)
        device.resume(pid)
        print(f"✓ 应用已启动 (PID: {pid})")
    
    # 加载脚本
    print("\n📜 加载Hook脚本...")
    script = session.create_script(js_code)
    script.on('message', on_message)
    script.load()
    print("✓ Hook脚本已加载")
    
    print("\n" + "=" * 80)
    print("✅ Hook已激活！")
    print("=" * 80)
    print("\n请在应用中执行以下操作:")
    print("  1. 登录账号")
    print("  2. 注册新用户")
    print("  3. 提交表单")
    print("  4. 或任何会触发数美SDK的操作")
    print("\n等待捕获数据...\n")
    print("=" * 80)
    
    # 保持运行
    sys.stdin.read()
    
except KeyboardInterrupt:
    print("\n\n⚠️  用户中断")
    if captured_data['aes_key']:
        print("\n已捕获的数据:")
        print(f"  AES密钥: {captured_data['aes_key']}")
        if captured_data['iv']:
            print(f"  IV: {captured_data['iv']}")
    sys.exit(0)
except Exception as e:
    print(f"\n❌ 错误: {e}")
    import traceback
    traceback.print_exc()
    sys.exit(1)

